package net.esj.basic.dao.hibernate;

import java.io.Serializable;
import java.util.Collection;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

@SuppressWarnings("unused")
public class Hibernate4SessionLocale implements HibernateSessionLocale {

	
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}



	@Override
	public Session getCurrentSession() {
		try{
			return sessionFactory.getCurrentSession();
		}catch(HibernateException e){
			return SessionFactoryUtils.openSession(sessionFactory);
		}
	}



	@Override
	public void delete(Object entity) {
		getCurrentSession().delete(entity);
	}



	@Override
	public void deleteAll(Collection c) {
		for (Object entity : c) {
			getCurrentSession().delete(entity);
		}
	}



	@Override
	public void flush() {
		getCurrentSession().flush();
	}



	@Override
	public <T> T get(Serializable id, Class<T> clazz) {
		return (T) getCurrentSession().get(clazz, id);
	}

	@Override
	public <T> T load(Serializable id, Class<T> clazz) {
		return (T) getCurrentSession().load(clazz, id);
	}


	@Override
	public Serializable save(Object entity) {
		return getCurrentSession().save(entity);
	}



	@Override
	public void saveOrUpdate(Object entity) {
		getCurrentSession().saveOrUpdate(entity);
	}



	@Override
	public void update(Object entity) {
		getCurrentSession().update(entity);
	}



	@Override
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}


}

